package com.ultrasoft.farmasoft.web;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
//import java.util.Enumeration;


import com.ultrasoft.farmasoft.domain.Pharmacy;
import com.ultrasoft.farmasoft.domain.Parameter;
//import com.ultrasoft.farmasoft.domain.Rol;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
//import com.ultrasoft.farmasoft.domain.Userprovider;
//import com.ultrasoft.farmasoft.domain.UserproviderPK;
import com.ultrasoft.farmasoft.service.CompanyOperationsService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;
//import com.ultrasoft.farmasoft.util.UtilUseFulTree;
//import com.ultrasoft.farmasoft.validator.AccessValidator;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

@Controller
@SessionAttributes({"s_UserPharmacy"})
@RequestMapping(value="/Company") /*name controler*/
public class OperationCompanyController implements ServletContextAware {
	
	private final CompanyOperationsService companyTransactionService;
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	private ServletContext servletContext; /*Para las imagenes*/

	@Autowired
    public OperationCompanyController(CompanyOperationsService companyTransactionService) {
        this.companyTransactionService = companyTransactionService;
    }
	/*****************************************************************/
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;

	}
	
	//  e:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\farmasoft\resources\imageCompany\ revisar 
	private void saveImage(String filename, MultipartFile imagen,HttpServletRequest request)throws RuntimeException, IOException {
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
			System.out.println(basePath);
			//File file = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+filename);
			File file = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+s_pharmacyId+"_mainLogo_"+filename); /*Guardando el archivo con el nombre -- 1_mainLogo_1.png*/
			FileUtils.writeByteArrayToFile(file, imagen.getBytes());
			System.out.println("Localizacion del Archivo almacenado:  " + file.toString());
		} catch (IOException e) {
			throw e;
		}
	}
	private void validateImage(MultipartFile imagen) {
		if (!(imagen.getContentType().equals("image/jpeg")||  
				imagen.getContentType().equals("image/png")||imagen.getContentType().equals("image/gif"))) {
			throw new RuntimeException("Solo Imagenes JPG, PNG, GIF son Aceptados");
		}
	}
		
	//For image 2
	private void saveImage2(String filename, MultipartFile myReportLogo,HttpServletRequest request)throws RuntimeException, IOException {
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
			System.out.println(basePath);
			
			File file = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+s_pharmacyId+"_reportLogo_"+filename);
			FileUtils.writeByteArrayToFile(file, myReportLogo.getBytes());
			System.out.println("Localizacion del Archivo almacenado:  " + file.toString());
		} catch (IOException e) {
			throw e;
		}
	}
	private void validateImage2(MultipartFile myReportLogo) {
		if (!(myReportLogo.getContentType().equals("image/jpeg")||  
				myReportLogo.getContentType().equals("image/png")||myReportLogo.getContentType().equals("image/gif"))) {
			throw new RuntimeException("Solo Imagenes JPG, PNG, GIF son Aceptados");
		}
	}
	
	//For image 3
	private void saveImage3(String filename, MultipartFile myLogo,HttpServletRequest request)throws RuntimeException, IOException {
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
			System.out.println(basePath);
			
			File file = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+s_pharmacyId+"_logo_"+filename);
			FileUtils.writeByteArrayToFile(file, myLogo.getBytes());
			System.out.println("Localizacion del Archivo almacenado:  " + file.toString());
		} catch (IOException e) {
			throw e;
		}
	}
	private void validateImage3(MultipartFile myLogo) {
		if (!(myLogo.getContentType().equals("image/jpeg")||  
				myLogo.getContentType().equals("image/png")||myLogo.getContentType().equals("image/gif"))) {
			throw new RuntimeException("Solo Imagenes JPG, PNG, GIF son Aceptados");
		}
	}
	/****************************************************************/
	
	private String redirectCompany(HttpServletRequest request){
		 if(!sessionControl(request))
			 return "redirect:/index"; 
		 else
			 return "redirect:/Company/infoCompany?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	 }
	private String handleRedirectCompany(HttpServletRequest request,String headMain) {
   	try {
   		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+
   				"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_)+
   				"&"+UtilCommon.optionId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.optionId_); 
		} catch (Exception e) {
			return redirectCompany(request);
		}
   }
	
	//start esencial
	private String redirectHumanResources(HttpServletRequest request){
		return "redirect:/configActivePrinciple?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	
	private String handleRedirectHumanResources(HttpServletRequest request,String headMainList) {
   	try {
   		return "redirect:/"+headMainList+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
		}catch (Exception e) {
			return redirectHumanResources(request);
		}
   }
	//Control main page OPERCOMPANY
	@RequestMapping(value="/operCompany", method = RequestMethod.GET)	
	public String handleFront1(SessionStatus status,HttpServletRequest request, Model model)throws ServletException  {
		if(this.sessionControl(request)){
			return UtilCommon.fOperation_Company+"operCompany";
	    }
		else 
			return redirectHumanResources(request);
	}			
	
	//INFORMATION COMPANY
		@RequestMapping(value="/infoCompany", method=RequestMethod.GET)
		public String handleRequestInformationCompany(SessionStatus status,HttpServletRequest request, Model model)throws ServletException  {
			if(this.sessionControl(request)){
		
				List<Pharmacy> pharmacyone = companyTransactionService.getOneListPharmacy(s_pharmacyId);
				model.addAttribute("ActivePharmacy",pharmacyone);
							
				Pharmacy p = companyTransactionService.searchPharmacyByID(s_pharmacyId);
				
				return UtilCommon.fOperation_Company_InformationCompany+"infoCompany";
		    }
			else 
				return redirectHumanResources(request);
		}
	
		// Edit company
		@RequestMapping(value="/companyEdit", method=RequestMethod.GET)
		public String handleRequestManagerCompanyEdit(HttpServletRequest request, @RequestParam Integer _pharmacyId, Model model) throws ServletException {
			
			if(this.sessionControl(request)){
				
				List<Pharmacy> pharmacyone = companyTransactionService.getOneListPharmacy(_pharmacyId);
				model.addAttribute("ActivePharmacy",pharmacyone);			
				
				return UtilCommon.fOperation_Company_InformationCompany+"editCompany";
		    }
			else 
				return redirectHumanResources(request);
		}
	
		//myReportLogo     myLogo
		 @RequestMapping(value="/companyEdit" , method = RequestMethod.POST)
		 public String onSubmitRequestManagerCompanyEdit(HttpServletRequest request,@RequestParam String action, @RequestParam String website, @RequestParam Integer idPharmacy, @RequestParam String name, @RequestParam String socialReason, @RequestParam String initials, @RequestParam String address,@RequestParam String birthdate, @RequestParam String email, @RequestParam String emailRef, @RequestParam String nit, @RequestParam String phone, @RequestParam String phoneRef ,Model model,@RequestParam String imageMain,@RequestParam String imageReportLogo,@RequestParam String imageLogo, @RequestParam(value = "imagen", required = false) List<MultipartFile> image, @RequestParam(value = "myReportLogo", required = false) List<MultipartFile> image2 , @RequestParam(value = "myLogo", required = false) List<MultipartFile> image3){
			 if( !action.equals("Cancelar")){ 
				 String picture="";
				 String delete="";
				 String picture2="";
				 String picture3="";
				 if (!image.get(0).isEmpty()) {
					 try {
						 for (MultipartFile multipartFile : image) {
							 validateImage(multipartFile);
							 //picture="resources/image/"+multipartFile.getOriginalFilename();
							 picture=idPharmacy+"_mainLogo_"+multipartFile.getOriginalFilename();/*Carga con este nombre  a la bds*/
							 File fichero = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+imageMain);
							 if (fichero.delete())
								System.out.println("El fichero ha sido borrado satisfactoriamente");
						     else
						        System.out.println("El fichero no puede ser borrado");
						}
					} catch (RuntimeException re) {}
				}
				 
				 if (!image2.get(0).isEmpty()) {
					 try {
						 for (MultipartFile multipartFile : image2) {
							 validateImage2(multipartFile);
							 picture2=idPharmacy+"_reportLogo_"+multipartFile.getOriginalFilename();
							 File fichero2 = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+imageReportLogo);
							 fichero2.delete();
						}
					} catch (RuntimeException re) {}
				}
				 
				 if (!image3.get(0).isEmpty()) {
					 try {
						 for (MultipartFile multipartFile : image3) {
							 validateImage3(multipartFile);
							 picture3=idPharmacy+"_logo_"+multipartFile.getOriginalFilename();
							 
							 File fichero3 = new File(servletContext.getRealPath("/")+"/resources/imageCompany/"+imageLogo);
							 fichero3.delete();
						}
					} catch (RuntimeException re) {}
				}
				
		    	Pharmacy phar= companyTransactionService.searchPharmacyByID(idPharmacy);
				phar.setName(name);
				phar.setNit(nit);
				phar.setEmail(email);
				phar.setEmail2(emailRef);
				phar.setPhone(phone);
				phar.setPhone2(phoneRef);
				phar.setInitials(initials);
				phar.setSocialReason(socialReason);
				phar.setWebsite(website);
				phar.setAddress(address);
				phar.setDateCreation(UtilConverter.converterStringToDate(request, "birthdate"));
				
				if(!image.get(0).isEmpty())
					phar.setMainImage(picture);				
				try {
					for (MultipartFile multipartFile : image) {
						saveImage(multipartFile.getOriginalFilename(), multipartFile,request);
						
					}
		    	} catch (IOException e) {
		    		System.out.println("No subio un imagen");
		    	}
				
				//Imagen 2
				if(!image2.get(0).isEmpty())
					phar.setReportLogo(picture2);				
				try {
					for (MultipartFile multipartFile : image2) {
						saveImage2(multipartFile.getOriginalFilename(), multipartFile,request);
					}
					
		    	} catch (IOException e) {
		    		System.out.println("No subio ninguna imagen para reportes");
		    	}
				//Imagen 3
				if(!image3.get(0).isEmpty())
					phar.setLogo(picture3);				
				try {
					for (MultipartFile multipartFile : image3) {
						saveImage3(multipartFile.getOriginalFilename(), multipartFile,request);
					}
					
		    	} catch (IOException e) {
		    		System.out.println("No subio ningun logo");
		    	}
				
				companyTransactionService.updatePharmacy(phar);
			 }
			return  handleRedirectCompany(request, "Company/infoCompany?");
		 }
	   
		//PARAMETERS COMPANY
			@RequestMapping(value="/paramsCompany", method=RequestMethod.GET)
			public String handleRequestAdminHumanResources(SessionStatus status,HttpServletRequest request, Model model)throws ServletException  {
				if(this.sessionControl(request)){
					
					List<Parameter> typeParameter= companyTransactionService.getDistParameterWithIdTypeParameterIdPharmacy(s_pharmacyId);
					model.addAttribute("distinctTypeParameter",typeParameter);

					List<Parameter> typepa= companyTransactionService.getListParameterWithIdPharmacy(s_pharmacyId);
					model.addAttribute("parametros",typepa );
					
					return UtilCommon.fOperation_Company_ParamsCompany+"paramsCompany";
			    }
				else 
					return redirectHumanResources(request);
			}
			@RequestMapping(value = "/operationsParamsEditCompany", method = RequestMethod.POST)
		   	public @ResponseBody String handleRequestOperationsParamsEditCompany(@RequestParam short parameterId,@RequestParam Integer accion,@RequestParam String valueParameter,HttpServletRequest request){
		       	String msg="";       	
		       	if(accion == 1){
		       		msg="Se Edito ";
		       		Parameter pa= companyTransactionService.searchParameterById(parameterId);
		       		pa.setValueParameter(valueParameter);
		       		companyTransactionService.updateParameter(pa);
		       	}
		   		return msg+"correctamente!!!";
		    }
}
